package net.arogarth.aws.android.manager.dbmodels;

import java.util.ArrayList;
import java.util.List;

import net.arogarth.aws.android.manager.AwsManager;
import net.arogarth.aws.android.manager.DatabaseAdapter;
import android.content.ContentValues;
import android.database.Cursor;

public class Region extends DbObject {

	private Long id = null;
	private Long accountId = null;
	private String region = "";
	
	public synchronized Long getId() {
		return id;
	}

	public synchronized void setId(Long id) {
		this.id = id;
	}

	public synchronized Long getAccountId() {
		return accountId;
	}

	public synchronized void setAccountId(Long accountId) {
		this.accountId = accountId;
	}

	public synchronized String getRegion() {
		return region;
	}

	public synchronized void setRegion(String region) {
		this.region = region;
	}

	@Override
	public DbObject load(Long id) {
		@SuppressWarnings("unchecked")
		List<AwsAccount> list = (List<AwsAccount>) this.list(String.format("id = %s", id));
		if(list.size() > 0) return list.get(0);
		
		return null;
	}

	public List<?> list() {
		return list(String.format("account_id = %s", AwsManager.getCurrentAwsAccount().getId()));
	}
	
	@Override
	public List<?> list(String where) {
		String qry = "SELECT * FROM " + DatabaseAdapter.APP_DB_TABLE_REGIONS;
		if(where != "")
			qry += " WHERE " + where;
		
		DatabaseAdapter dba = new DatabaseAdapter().open();
		Cursor c = dba.getDatabase().rawQuery(qry, new String[] {});
		
		List<Region> regions = new ArrayList<Region>();

		while(c.moveToNext()) {
			Long id = c.getLong(0);
			Long accountId = c.getLong(1);
			String region = c.getString(2);
			
			Region oRegion = new Region();
			oRegion.setId(id);
			oRegion.setAccountId(accountId);
			oRegion.setRegion(region);
			regions.add(oRegion);
		}
		
		dba.close();
		return regions;
	}

	@Override
	public void save() {
		DatabaseAdapter dba = new DatabaseAdapter().open();
		if(this.id == null) { // Save
			
			ContentValues values = new ContentValues();
			values.put("account_id", this.accountId);
			values.put("region", this.region);
			this.id = dba.getDatabase().insert(DatabaseAdapter.APP_DB_TABLE_REGIONS, "0", values);
			
		} else { // Update
			
			String qry = "UPDATE " + DatabaseAdapter.APP_DB_TABLE_REGIONS;
			qry += " SET ";
			qry += String.format("region = '%s',", this.region);
			qry += String.format("account_id = '%s',", this.accountId);
			qry += " WHERE id = " + this.id;
			dba.getDatabase().execSQL(qry);
			
		}
		
		dba.close();
	}

	@Override
	public void delete() {
		DatabaseAdapter dba = new DatabaseAdapter().open();
		dba.getDatabase().delete(DatabaseAdapter.APP_DB_TABLE_REGIONS, "id = " + this.id.toString(), new String[] { });
		this.id = null;
		dba.close();
	}

}
